import { CacheService } from './cacheService';
import { BatchService } from './batchService';
import { MonitorService } from './monitorService';
import { SecurityService } from './securityService';
import { GeoLocationService } from './geoLocationService';
import { AlertService } from './alertService';
import { AlertLevel } from '../types/alert';
import { performanceConfig } from '../config/performanceConfig';
import prisma from '../lib/prisma';

export class ServiceManager {
  private static instance: ServiceManager;
  private initialized = false;

  private constructor() {}

  public static getInstance(): ServiceManager {
    if (!ServiceManager.instance) {
      ServiceManager.instance = new ServiceManager();
    }
    return ServiceManager.instance;
  }

  // 初始化所有服务
  public async initialize(): Promise<void> {
    if (this.initialized) {
      return;
    }

    try {
      // 初始化监控服务
      const monitorService = MonitorService.getInstance();
      
      // 初始化缓存服务
      const cacheService = CacheService.getInstance({
        ttl: performanceConfig.cache.localTTL,
        useRedis: performanceConfig.cache.useRedis,
        redisUrl: performanceConfig.cache.redisUrl,
        checkperiod: Math.floor(performanceConfig.cache.localTTL * 0.2)
      });

      // 初始化基础服务
      const alertService = AlertService.getInstance();
      SecurityService.getInstance();
      const geoLocationService = GeoLocationService.getInstance();

      // 初始化并预热地理位置服务
      await geoLocationService.warmupLocalDB();

      // 注册监控回调
      monitorService.onMetricsUpdate(metrics => {
        // 检查性能指标
        if (metrics.cpu > performanceConfig.monitor.alertThresholds.cpu) {
          alertService.sendAlert({
            title: 'CPU使用率过高',
            body: `当前CPU使用率: ${metrics.cpu}%`,
            level: AlertLevel.WARNING,
            source: 'monitor'
          });
        }

        if (metrics.memory.used / metrics.memory.total > performanceConfig.monitor.alertThresholds.memory / 100) {
          alertService.sendAlert({
            title: '内存使用率过高',
            body: `当前内存使用率: ${(metrics.memory.used / metrics.memory.total * 100).toFixed(2)}%`,
            level: AlertLevel.WARNING,
            source: 'monitor'
          });
        }

        // 缓存性能指标
        cacheService.set('system:metrics:latest', metrics, 300);
      });

      // 启动定期清理任务
      this.startCleanupTasks();

      this.initialized = true;
      console.log('所有服务初始化完成');

    } catch (error) {
      console.error('服务初始化失败:', error);
      throw error;
    }
  }

  // 清理任务
  private startCleanupTasks(): void {
    // 每小时清理过期的缓存
    setInterval(() => {
      const cacheService = CacheService.getInstance();
      cacheService.clear();
    }, 60 * 60 * 1000);

    // 每天凌晨3点执行数据库清理
    const scheduleDbCleanup = () => {
      const now = new Date();
      const nextRun = new Date(
        now.getFullYear(),
        now.getMonth(),
        now.getDate() + 1,
        3, 0, 0
      );
      const delay = nextRun.getTime() - now.getTime();

      setTimeout(() => {
        this.cleanupDatabase();
        scheduleDbCleanup();
      }, delay);
    };

    scheduleDbCleanup();
  }

  // 数据库清理
  private async cleanupDatabase(): Promise<void> {
    try {
      // 清理30天前的日志和软删除的问题
      const thirtyDaysAgo = new Date();
      thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);

      // 使用原始SQL查询进行清理
      const queries = [
        // 清理审计日志
        prisma.$executeRaw`DELETE FROM "AuditLog" WHERE "createdAt" < ${thirtyDaysAgo}`,
        
        // 清理已软删除的题目
        prisma.$executeRaw`DELETE FROM "Question" WHERE deleted = true AND "deletedAt" < ${thirtyDaysAgo}`
      ];

      await prisma.$transaction(queries);

      console.log('数据库清理完成');
    } catch (error) {
      const err = error as Error;
      console.error('数据库清理失败:', err);
      
      // 发送告警
      const alertService = AlertService.getInstance();
      alertService.sendAlert({
        title: '数据库清理失败',
        body: `清理任务执行失败: ${err.message}`,
        level: AlertLevel.ERROR,
        source: 'database'
      });
    }
  }

  // 优雅关闭
  public async shutdown(): Promise<void> {
    try {
      // 停止监控服务
      const monitorService = MonitorService.getInstance();
      monitorService.stop();

      // 关闭缓存连接
      const cacheService = CacheService.getInstance();
      await cacheService.clear();

      // 等待所有批处理任务完成
      const batchServices = this.getBatchServices();
      await Promise.all(
        batchServices.map(service => service.flush())
      );

      // 关闭 Prisma 客户端
      await prisma.$disconnect();

      console.log('所有服务已安全关闭');
    } catch (error) {
      console.error('服务关闭过程中出错:', error);
      throw error;
    }
  }

  // 获取所有批处理服务实例
  private getBatchServices(): BatchService<any>[] {
    // 这里需要返回所有使用BatchService的服务实例
    return [];
  }
}
